package com.playcrab.adouban;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.google.gdata.client.douban.DoubanService;
import com.google.gdata.data.Person;
import com.google.gdata.data.douban.Attribute;
import com.google.gdata.data.douban.DoumailEntry;
import com.google.gdata.data.douban.DoumailFeed;
import com.google.gdata.data.douban.Entity;
import com.google.gdata.data.douban.Subject;
import com.google.gdata.util.ServiceException;
import com.playcrab.adouban.R.color;
import com.playcrab.adouban.util.DateTimeUtil;

public class DoumailList extends BaseActivity {
	private static final int COUNT_ITEMS_PER_PAGE = 15;
	private static final String LOG_TAG = "DoumailList";

	private ListView doumailList;
	private ProgressDialog progressDialog = null;
	DoumailListAdapter doumailListAdapter = null;
	private Handler handler = new Handler();
	String query;
	String type;
	DoumailFeed feed;
	List<DoumailEntry> doumails;

	public List<DoumailEntry> getDoumails() {
		return doumails;
	}

	public void setDoumails(List<DoumailEntry> doumails) {
		this.doumails = doumails;
	}

	int currentStartIndex = 1;

	private static final int MENU_SEARCH = Menu.FIRST + 1;
	private static final int MENU_SCAN = Menu.FIRST + 2;

	public static final int MENU_RETURN = Menu.FIRST + 10;

	public static final int MENU_REPLY = Menu.FIRST + 7;
	public static final int MENU_DELETE = Menu.FIRST + 8;
	private static final int MENU_VIEW_DOUMAIL = Menu.FIRST + 100;
	private static final int MENU_DELETE_DOUMAIL = Menu.FIRST + 101;
	private static final int MENU_VIEW_DOUBAN = Menu.FIRST + 102;
	private static final int MENU_VIEW_USER = Menu.FIRST + 105;
	private static final int MENU_EXIT = Menu.FIRST + 103;
	private static final int MENU_REFRESH = Menu.FIRST + 104;
	public class DoumailListAdapter extends AutoRefreshAdapter<DoumailEntry> {

		private static final String LOG_TAG = "DoumailListAdapter";
		Activity context;
		LayoutInflater inflater;
		WebView userIcon;
		TextView username, replyTo, updateBody, via, timestamp;
		List<DoumailEntry> more_cols;

		public DoumailListAdapter(Activity context, List<DoumailEntry> doumails) {
			super(context, doumails);
			inflater = LayoutInflater.from(context);

			this.context = context;
			this.itemList = doumails;
			// TODO Auto-generated constructor stub
		}

		public String getDoumailInfo(DoumailEntry se) {
			return "";
		}

		@Override
		public View getItemView(int position) {
			View row = inflater.inflate(R.layout.doumail_row, null);
			row.setClickable(true);
			row.setLongClickable(true);
			final DoumailEntry se = itemList.get(position);
			
			row.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO: onclick of item
					String sid =  se.getId().substring(se.getId().lastIndexOf('/')+1);
					Intent i = new Intent(DoumailList.this, ViewDoumail.class);
					i.putExtra("id", sid );
					i.putExtra("type", type );
					startActivity(i);
				}

			});

			row.setTag(se);
			if (se == null) {
				return row;
			} 
		
		//	layout.setBackgroundColor(android.R.color.white);
				 

			TextView doumail_title = (TextView) row
					.findViewById(R.id.doumail_title);
			TextView doumail_author = (TextView) row
					.findViewById(R.id.doumail_author);
			TextView doumail_published = (TextView) row
					.findViewById(R.id.doumail_published);
			
			
			if (se.getTitle() != null) {
				doumail_title.setText(se.getTitle().getPlainText());
			} 
			
			Person p=null;
			if(DoumailList.this.type.equals("inbox")){
				p = se.getAuthors().get(0);
				if(p!=null){
					doumail_author.setText(p.getName() );
	 			}
			}else if(DoumailList.this.type.equals("outbox")){
				p = se.getReceiver();
				if(p!=null){
					doumail_author.setText(">>"+p.getName() );
	 			}
				
			}
			
			 
			
			if (se.getPublished() != null) {
				doumail_published.setText(DateTimeUtil.simpleFormat(se
						.getPublished()));
			}
			
			LinearLayout layout = (LinearLayout)row.findViewById(R.id.doumail_row);
			if( se.getUnread() ){
				layout.setBackgroundColor(Color.DKGRAY); 
			}  
			return row;

		}
		
		public void removeDoumail(String id) {
			for(int i=0; i< itemList.size(); i++){
				DoumailEntry e = itemList.get(i);
			   if(e.getId().equalsIgnoreCase(id)){
				   itemList.remove(i);
				   notifyDataSetChanged();
				   break;
			   } 
			}
			
		}

		public void addDoumails(List<DoumailEntry> subs) {
			// TODO Auto-generated method stub
			itemList.addAll(itemList.size(), subs);
			notifyDataSetChanged();
		}

		protected boolean cacheInBackground() {
			more_cols = DoumailList.this.updateDoumails();

			return (more_cols.size() == DoumailList.COUNT_ITEMS_PER_PAGE);
		}

		protected void appendCachedData() {
			addDoumails(more_cols);
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.doumail_list);
		
		setTitle(getString(R.string.doumail));

		Bundle bundle = this.getIntent().getExtras();
		type = bundle.getString("type");

		doumailList = (ListView) findViewById(R.id.doumail_list);

		registerForContextMenu(doumailList);
		
		doumailListAdapter = new DoumailListAdapter(
				DoumailList.this, new ArrayList<DoumailEntry>());
		doumailList.setAdapter(doumailListAdapter);

//		progressDialog = ProgressDialog.show(DoumailList.this, DoumailList.this
//				.getResources().getText(R.string.waiting), DoumailList.this
//				.getResources().getText(R.string.searching), true);
//
//		new Thread() {
//			public void run() {
//				doumails = updateDoumails();
//				progressDialog.dismiss();
//				handler.post(new Runnable() {
//					public void run() {
//						doumailListAdapter = new DoumailListAdapter(
//								DoumailList.this, doumails);
//						doumailList.setAdapter(doumailListAdapter);
//					}
//				});
//
//			}
//		}.start();

		InsertPanel();
	}
	
	public void refreshDoumails(){
		if (this.doumailListAdapter == null
				|| this.doumailListAdapter.itemList == null)
			return ;
		
		
		Toast.makeText(
				getApplicationContext(),
				this.getResources().getText(
						R.string.waiting),
				Toast.LENGTH_SHORT).show();
 
		new Thread() {
			public void run() { 
				doumails = updateDoumails(1); 
				DoumailList.this.doumailListAdapter.itemList.clear();
				DoumailList.this.doumailListAdapter.itemList.addAll(doumails);
				handler.post(new Runnable() {
					public void run() {  
						DoumailList.this.doumailListAdapter.notifyDataSetChanged();
					}
				});
			 
			}
		}.start(); 
		 
	}
	
	protected List<DoumailEntry> updateDoumails(int startIndex) {
		currentStartIndex = startIndex; 
		String userId = getStoredUserId();
		DoubanService service = getAuthedDoubanService();// DoubanAPI.getInstance().getService();
		if (service == null) {
			return new ArrayList();
		}
		try {
			if(type.equals("inbox")){
				feed = service.getDoumailInbox(DoumailList.this.currentStartIndex,
					COUNT_ITEMS_PER_PAGE);
			}else if(type.equals("outbox")){
				feed = service.getDoumailOutbox(DoumailList.this.currentStartIndex,
						COUNT_ITEMS_PER_PAGE);
			}else if(type.equals("unread")){
				feed = service.getDoumailInboxUnread(DoumailList.this.currentStartIndex,
						COUNT_ITEMS_PER_PAGE);
			}
			doumails = feed.getEntries();
			return doumails;

		} catch (IOException e) {
			e.printStackTrace();
			this.showInfo(getString(R.string.network_error));
		} catch (ServiceException e) {
			e.printStackTrace();
			this.showInfo(getString(R.string.service_error));
		} finally {
		}
		return new ArrayList();
	}

	protected List<DoumailEntry> updateDoumails() {
		int currentStartIndex = 1;
		if (this.doumailListAdapter == null
				|| this.doumailListAdapter.itemList == null)
			currentStartIndex = 1;
		else
			currentStartIndex = this.doumailListAdapter.itemList.size() + 1;

		 
		return   updateDoumails(currentStartIndex);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("操作菜单");
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		menu.add(0, MENU_VIEW_DOUMAIL, 0, "查看豆邮");
		menu.add(0, MENU_DELETE_DOUMAIL, 0, "删除豆邮");
		DoumailEntry doumail = this.doumailListAdapter.itemList.get(info.position);
		Person p=null;
		if(this.type.equals("inbox")){
		    p = doumail.getAuthors().get(0);
			
		 }else if(this.type.equals("outbox")){
			 p = doumail.getReceiver(); 
		 }
		final Person  author =p;
		if(p!=null){
			 MenuItem item =  menu.add(0, MENU_VIEW_USER, 0, author.getName() );
			 item.setOnMenuItemClickListener(new OnMenuItemClickListener(){ 
					@Override
					public boolean onMenuItemClick(MenuItem i) {  
						String sid = author.getUri().substring(author.getUri().lastIndexOf('/')+1); 
						DoumailList.this.viewUser(sid);
						return false;
					}
			 });
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		DoumailEntry se = this.doumailListAdapter.itemList.get(info.position);
		switch (item.getItemId()) {
		case MENU_VIEW_DOUMAIL: {
			String sid =  se.getId().substring(se.getId().lastIndexOf('/')+1);
			Intent i = new Intent(DoumailList.this, ViewDoumail.class);
			i.putExtra("id", sid );
			i.putExtra("type", type );
			startActivity(i);
			return true;
		}
		case MENU_DELETE_DOUMAIL: { 
			this.deleteDoumail(se);
			return true;

		}

		}
		return super.onOptionsItemSelected(item);

	}
	public void deleteDoumail(DoumailEntry de){
		Toast.makeText(
				getApplicationContext(),
				this.getResources().getText(
						R.string.deleting),
				Toast.LENGTH_SHORT).show();
		final String id  = de.getId();
		new Thread() {
			public void run() {
				DoubanService service = getAuthedDoubanService();
				try {
					service.deleteDoumail(id);
				} catch (MalformedURLException e) { 
					DoumailList.this.showInfo(DoumailList.this.getString(R.string.service_error));
				} catch (IOException e) { 
					DoumailList.this.showInfo(DoumailList.this.getString(R.string.network_error));
				} catch (ServiceException e) { 
					DoumailList.this.showInfo(DoumailList.this.getString(R.string.service_error));
				} 
				handler.post(new Runnable() {
					public void run() { 
						DoumailList.this.doumailListAdapter.removeDoumail(id);
					}
				});

			}
		}.start();
	}
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_REFRESH: {
			this.refreshDoumails();
			return true;
		}
		case MENU_EXIT: {
			this.finish();
		}

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_REFRESH, 0, "刷新").setIcon(android.R.drawable.ic_menu_rotate)
		.setAlphabeticShortcut('R'); 
		menu.add(0, MENU_EXIT, 0, "返回").setIcon(android.R.drawable.ic_menu_close_clear_cancel)
				.setAlphabeticShortcut('X'); 
		return true;
	}

}
